'use strict';
/**
 * chen.pian
 */
angular.module('app.lib', []);
angular.module('app.lib').factory('httpInterceptor', httpInterceptor);
httpInterceptor.$injector = ['$log', '$q', '$injector', '$rootScope'];
function httpInterceptor($log, $q, $injector, $rootScope) {
  var interceptors = {
    request: function(config) {
      var deferred = $q.defer();
      if (config.url.indexOf(".") == -1 || config.url == "logout") {
        $rootScope.loading = $rootScope.loading ? $rootScope.loading + 1 : 1;
        $rootScope.loadingLayerIndex = layer.load(2);
      }
      deferred.resolve(config);
      return deferred.promise;
    },
    requestError: function(config) {
      return config;
    },
    response: function(response) {
      var deferred = $q.defer();
      if (response.status == 200) {
        if (response.config.url.indexOf(".") == -1) {
          $rootScope.loading--;
          if ($rootScope.loading == 0) {
            layer.close($rootScope.loadingLayerIndex);
          }
          if (response.data.code == "0") {
            layer.alert(response.data.errorMsg,{"title":"错误信息"})
            deferred.reject(response);
          } else {
            deferred.resolve(response);
          }
        } else {
          deferred.resolve(response);
        }
      }
      return deferred.promise;
    },
    responseError: function(rejection) {
      $rootScope.loading--;
      layer.close($rootScope.loadingLayerIndex);
      layer.msg(rejection.status);
      $rootScope.$broadcast({
              401:"page:notAuthorized", 
              404:"page:notFound",  
              500:"server:error"
      }[rejection.status]);
      return $q.reject(rejection);
    }
  }
  return interceptors;
}